package by.vkhalko.asamo.dataaccess.impl;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import by.vkhalko.asamo.dataaccess.OrderDao;
import by.vkhalko.asamo.datamodel.Company;
import by.vkhalko.asamo.datamodel.Customer;
import by.vkhalko.asamo.datamodel.Customer_;
import by.vkhalko.asamo.datamodel.Order;
import by.vkhalko.asamo.datamodel.Order_;
import by.vkhalko.asamo.datamodel.Person;
import by.vkhalko.asamo.datamodel.Status;

@Repository
public class OrderDaoImpl extends AbstractDaoImpl<Long, Order> implements
		OrderDao {

	protected OrderDaoImpl() {
		super(Order.class);

	}

	@Override
	public List<Order> getAllByCompany(Company company) {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<Order> criteria = cBuilder.createQuery(Order.class);
		Root<Order> root = criteria.from(Order.class);
		Join<Order, Customer> details = root.join(Order_.customer);
		criteria.where(cBuilder.equal(details.get(Customer_.company), company));

		criteria.select(root);
		criteria.orderBy(cBuilder.asc(root.get(Order_.dateReceipt)));

		TypedQuery<Order> query = getEm().createQuery(criteria);
		List<Order> results = query.getResultList();

		return results;
	}

	@Override
	public List<Order> getAllByPerson(Person person) {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<Order> criteria = cBuilder.createQuery(Order.class);
		Root<Order> root = criteria.from(Order.class);
		Join<Order, Customer> details = root.join(Order_.customer);
		criteria.where(cBuilder.equal(details.get(Customer_.person), person));

		criteria.select(root);
		criteria.orderBy(cBuilder.asc(root.get(Order_.dateReceipt)));

		TypedQuery<Order> query = getEm().createQuery(criteria);
		List<Order> results = query.getResultList();

		return results;
	}

	@Override
	public List<Order> getAllByStatus(Status status) {
		return getAllByFieldRestriction(Order_.status, status);
	}

	@Override
	public List<Order> getAllOrders() {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<Order> criteria = cBuilder.createQuery(Order.class);
		Root<Order> root = criteria.from(Order.class);

		criteria.select(root);

		TypedQuery<Order> query = getEm().createQuery(criteria);
		List<Order> results = query.getResultList();
		return results;
	}

}
